package edu.biwu;

import edu.bw.model.Student;
import lombok.extern.log4j.Log4j2;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.InputStream;
import java.time.LocalDate;

@Log4j2
public class MybatisDemo02 {
    @Test
    public void testInsertStudent() {
        InputStream is = MybatisDemo02.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml");

        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        SqlSession sqlSession = sqlSessionFactory.openSession();

        try {
            Student student = new Student("国建", "男", LocalDate.parse("2005-09-01"));
            sqlSession.insert("test.insertStudent", student);
            sqlSession.commit();
            log.debug("Student{}", student);
        } catch (Exception e) {
            sqlSession.rollback();//如果插入发生问题，则回滚到之前的状态
            e.printStackTrace();
        }finally {
            sqlSession.close();//无论是否报错都要关闭会话释放资源
        }

    }

    @Test
    public void testUpdateStudent(){
        InputStream is = MybatisDemo02.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml");

        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        SqlSession sqlSession = sqlSessionFactory.openSession();

        try {
            sqlSession.update("test.updateStudent",
                    new Student(201312345,"唐国建","女",LocalDate.parse("2005-09-02")));
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }

    }

    @Test
    public void testDeleteStudent(){
        InputStream is = MybatisDemo02.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml");

        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        SqlSession sqlSession = sqlSessionFactory.openSession();

        try {
            sqlSession.delete("test.deleteStudent", 201312345);
            sqlSession.commit();
        } catch (Exception e) {
            sqlSession.rollback();
        } finally {
         sqlSession.close();
        }

    }
}
